package com.kyw.androidquicklib.retrofit;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitHelper {

    private static RetrofitHelper instance = null;
    private static OkHttpClient okHttpClient;
    public ApiService api;

    public RetrofitHelper(OkHttpClient okHttpClient){
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(ApiService.BASE_URL)//服务器地址
                .addConverterFactory(GsonConverterFactory.create())//用Gson把服务端返回的json数据解析成实体
                .client(okHttpClient)
                .build();//生成一个Retrofit实例
        api = retrofit.create(ApiService.class);//传入网络接口类,得到接口对象实例,调用接口类中的方法。
    }

    public static RetrofitHelper getInstance(){
        if (instance == null){
            instance = new RetrofitHelper(getOkhttpClient());
        }
        return instance;
    }
    public static ApiService getAPI(){
        return getInstance().api;
    }

    //okhttp连接的一些设置
    public static OkHttpClient getOkhttpClient(){
        okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(20, TimeUnit.SECONDS)//连接超时时间
                .readTimeout(20,TimeUnit.SECONDS)//读超时时间
                .writeTimeout(20,TimeUnit.SECONDS)//写超时时间
                .retryOnConnectionFailure(true)//失败重连
                .addInterceptor(new HttpLoggingInterceptor())
                .addInterceptor(headerInterceptor)//设置头信息
                .build();
        return okHttpClient;
    }
    /**
     * 设置头信息
     */
    static Interceptor headerInterceptor = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request originalRequest = chain.request();
            Request.Builder requestBuilder = originalRequest.newBuilder()
//                    .addHeader("Accept-Encoding", "gzip")
                    .addHeader("Accept", "application/json")
                    .addHeader("Content-Type", "text/plain; charset=utf-8")
                    .method(originalRequest.method(), originalRequest.body());
            Request request = requestBuilder.build();
            return chain.proceed(request);
        }
    };
}